<template>
  <div class="warehouse-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>仓库档案管理</h2>
      <p>管理仓库基础信息，包括仓库位置、容量、管理员等</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="仓库编码">
            <el-input v-model="searchForm.warehouseCode" placeholder="请输入仓库编码" clearable />
          </el-form-item>
          <el-form-item label="仓库名称">
            <el-input v-model="searchForm.warehouseName" placeholder="请输入仓库名称" clearable />
          </el-form-item>
          <el-form-item label="仓库类型">
            <el-select v-model="searchForm.warehouseType" placeholder="请选择类型" clearable>
              <el-option label="原料仓库" value="raw_material" />
              <el-option label="成品仓库" value="finished_goods" />
              <el-option label="半成品仓库" value="semi_finished" />
              <el-option label="备件仓库" value="spare_parts" />
              <el-option label="退货仓库" value="return_goods" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库状态">
            <el-select v-model="searchForm.warehouseStatus" placeholder="请选择状态" clearable>
              <el-option label="正常" value="active" />
              <el-option label="维护中" value="maintenance" />
              <el-option label="停用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增仓库
      </el-button>
      <el-button type="success" @click="handleBatchImport">
        <el-icon><Upload /></el-icon>
        批量导入
      </el-button>
      <el-button type="warning" @click="handleBatchExport">
        <el-icon><Download /></el-icon>
        批量导出
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouseCode" label="仓库编码" width="120" sortable />
        <el-table-column prop="warehouseName" label="仓库名称" min-width="180" />
        <el-table-column prop="warehouseType" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getWarehouseTypeColor(row.warehouseType)">{{ getWarehouseTypeLabel(row.warehouseType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="位置" min-width="200" />
        <el-table-column prop="manager" label="管理员" width="100" />
        <el-table-column prop="capacity" label="容量(m³)" width="100" sortable>
          <template #default="{ row }">
            {{ row.capacity.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="utilizationRate" label="利用率" width="100">
          <template #default="{ row }">
            <el-progress :percentage="row.utilizationRate" :color="getUtilizationColor(row.utilizationRate)" />
          </template>
        </el-table-column>
        <el-table-column prop="warehouseStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getWarehouseStatusColor(row.warehouseStatus)">
              {{ getWarehouseStatusLabel(row.warehouseStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" sortable />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 仓库详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="warehouse-form"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="仓库编码" prop="warehouseCode">
                  <el-input v-model="formData.warehouseCode" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库名称" prop="warehouseName">
                  <el-input v-model="formData.warehouseName" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="仓库类型" prop="warehouseType">
                  <el-select v-model="formData.warehouseType" :disabled="dialogMode === 'view'" style="width: 100%">
                    <el-option label="原料仓库" value="raw_material" />
                    <el-option label="成品仓库" value="finished_goods" />
                    <el-option label="半成品仓库" value="semi_finished" />
                    <el-option label="备件仓库" value="spare_parts" />
                    <el-option label="退货仓库" value="return_goods" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库状态" prop="warehouseStatus">
                  <el-select v-model="formData.warehouseStatus" :disabled="dialogMode === 'view'" style="width: 100%">
                    <el-option label="正常" value="active" />
                    <el-option label="维护中" value="maintenance" />
                    <el-option label="停用" value="inactive" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="仓库管理员" prop="manager">
                  <el-input v-model="formData.manager" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="formData.contactPhone" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="位置信息" name="location">
            <el-form-item label="详细地址" prop="location">
              <el-input v-model="formData.location" :disabled="dialogMode === 'view'" />
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="省份" prop="province">
                  <el-select v-model="formData.province" :disabled="dialogMode === 'view'" style="width: 100%">
                    <el-option label="北京市" value="beijing" />
                    <el-option label="上海市" value="shanghai" />
                    <el-option label="广东省" value="guangdong" />
                    <el-option label="江苏省" value="jiangsu" />
                    <el-option label="浙江省" value="zhejiang" />
                    <el-option label="山东省" value="shandong" />
                    <el-option label="河南省" value="henan" />
                    <el-option label="四川省" value="sichuan" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="城市" prop="city">
                  <el-input v-model="formData.city" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="邮政编码" prop="postalCode">
                  <el-input v-model="formData.postalCode" :disabled="dialogMode === 'view'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input-number v-model="formData.longitude" :disabled="dialogMode === 'view'" :precision="6" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input-number v-model="formData.latitude" :disabled="dialogMode === 'view'" :precision="6" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="容量信息" name="capacity">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="总容量(m³)" prop="capacity">
                  <el-input-number v-model="formData.capacity" :disabled="dialogMode === 'view'" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="已用容量(m³)" prop="usedCapacity">
                  <el-input-number v-model="formData.usedCapacity" :disabled="dialogMode === 'view'" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="货架数量" prop="shelfCount">
                  <el-input-number v-model="formData.shelfCount" :disabled="dialogMode === 'view'" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="货位数量" prop="locationCount">
                  <el-input-number v-model="formData.locationCount" :disabled="dialogMode === 'view'" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大载重(吨)" prop="maxWeight">
                  <el-input-number v-model="formData.maxWeight" :disabled="dialogMode === 'view'" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="温度范围" prop="temperatureRange">
                  <el-input v-model="formData.temperatureRange" :disabled="dialogMode === 'view'" placeholder="如：-18℃ ~ 25℃" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="设备信息" name="equipment">
            <el-form-item label="设备清单" prop="equipmentList">
              <el-input
                v-model="formData.equipmentList"
                type="textarea"
                :rows="4"
                :disabled="dialogMode === 'view'"
                placeholder="请输入仓库设备清单，如：叉车、货架、监控设备等"
              />
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="安全设施" prop="safetyFacilities">
                  <el-checkbox-group v-model="formData.safetyFacilities" :disabled="dialogMode === 'view'">
                    <el-checkbox label="fire_alarm">火警系统</el-checkbox>
                    <el-checkbox label="sprinkler">喷淋系统</el-checkbox>
                    <el-checkbox label="security_camera">监控系统</el-checkbox>
                    <el-checkbox label="access_control">门禁系统</el-checkbox>
                    <el-checkbox label="emergency_exit">紧急出口</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="特殊功能" prop="specialFeatures">
                  <el-checkbox-group v-model="formData.specialFeatures" :disabled="dialogMode === 'view'">
                    <el-checkbox label="temperature_control">温控</el-checkbox>
                    <el-checkbox label="humidity_control">湿度控制</el-checkbox>
                    <el-checkbox label="dust_proof">防尘</el-checkbox>
                    <el-checkbox label="anti_static">防静电</el-checkbox>
                    <el-checkbox label="explosion_proof">防爆</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="其他信息" name="other">
            <el-form-item label="建设时间" prop="constructionDate">
              <el-date-picker
                v-model="formData.constructionDate"
                type="date"
                :disabled="dialogMode === 'view'"
                placeholder="选择建设时间"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="租赁信息" prop="leaseInfo">
              <el-input
                v-model="formData.leaseInfo"
                type="textarea"
                :rows="3"
                :disabled="dialogMode === 'view'"
                placeholder="请输入租赁相关信息"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                :disabled="dialogMode === 'view'"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogMode !== 'view'" type="primary" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Upload, Download, Delete } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('add') // add, edit, view
const selectedRows = ref([])
const formRef = ref()
const activeTab = ref('basic')

// 搜索表单
const searchForm = reactive({
  warehouseCode: '',
  warehouseName: '',
  warehouseType: '',
  warehouseStatus: ''
})

// 表单数据
const formData = reactive({
  id: null,
  warehouseCode: '',
  warehouseName: '',
  warehouseType: '',
  warehouseStatus: 'active',
  manager: '',
  contactPhone: '',
  location: '',
  province: '',
  city: '',
  postalCode: '',
  longitude: null,
  latitude: null,
  capacity: 0,
  usedCapacity: 0,
  shelfCount: 0,
  locationCount: 0,
  maxWeight: 0,
  temperatureRange: '',
  equipmentList: '',
  safetyFacilities: [],
  specialFeatures: [],
  constructionDate: null,
  leaseInfo: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  warehouseCode: [
    { required: true, message: '请输入仓库编码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  warehouseType: [
    { required: true, message: '请选择仓库类型', trigger: 'change' }
  ],
  manager: [
    { required: true, message: '请输入仓库管理员', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 模拟数据
const mockData = [
  {
    id: 1,
    warehouseCode: 'WH001',
    warehouseName: '北京总仓',
    warehouseType: 'finished_goods',
    warehouseStatus: 'active',
    manager: '张三',
    contactPhone: '13800138001',
    location: '北京市朝阳区工业园区1号',
    province: 'beijing',
    city: '北京市',
    postalCode: '100000',
    longitude: 116.407526,
    latitude: 39.904030,
    capacity: 10000,
    usedCapacity: 7500,
    utilizationRate: 75,
    shelfCount: 200,
    locationCount: 1000,
    maxWeight: 500,
    temperatureRange: '5℃ ~ 25℃',
    equipmentList: '叉车×10、货架×200、监控设备×50、消防设备×20',
    safetyFacilities: ['fire_alarm', 'sprinkler', 'security_camera', 'access_control'],
    specialFeatures: ['temperature_control', 'dust_proof'],
    constructionDate: '2020-01-15',
    leaseInfo: '自有仓库',
    remark: '主要存储成品，配送全国',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    warehouseCode: 'WH002',
    warehouseName: '上海原料仓',
    warehouseType: 'raw_material',
    warehouseStatus: 'active',
    manager: '李四',
    contactPhone: '13900139002',
    location: '上海市浦东新区张江高科技园区2号',
    province: 'shanghai',
    city: '上海市',
    postalCode: '200000',
    longitude: 121.473701,
    latitude: 31.230416,
    capacity: 8000,
    usedCapacity: 6400,
    utilizationRate: 80,
    shelfCount: 150,
    locationCount: 800,
    maxWeight: 400,
    temperatureRange: '10℃ ~ 30℃',
    equipmentList: '叉车×8、货架×150、监控设备×40、消防设备×15',
    safetyFacilities: ['fire_alarm', 'sprinkler', 'security_camera'],
    specialFeatures: ['humidity_control', 'anti_static'],
    constructionDate: '2019-06-20',
    leaseInfo: '租赁期限：2019-2029年',
    remark: '主要存储原材料，供应华东地区',
    createTime: '2024-01-16 14:20:00'
  },
  {
    id: 3,
    warehouseCode: 'WH003',
    warehouseName: '广州配送中心',
    warehouseType: 'finished_goods',
    warehouseStatus: 'active',
    manager: '王五',
    contactPhone: '13700137003',
    location: '广州市天河区科技园南区3号',
    province: 'guangdong',
    city: '广州市',
    postalCode: '510000',
    longitude: 113.280637,
    latitude: 23.125178,
    capacity: 12000,
    usedCapacity: 9600,
    utilizationRate: 80,
    shelfCount: 250,
    locationCount: 1200,
    maxWeight: 600,
    temperatureRange: '15℃ ~ 35℃',
    equipmentList: '叉车×12、货架×250、监控设备×60、消防设备×25',
    safetyFacilities: ['fire_alarm', 'sprinkler', 'security_camera', 'access_control', 'emergency_exit'],
    specialFeatures: ['temperature_control', 'humidity_control'],
    constructionDate: '2021-03-10',
    leaseInfo: '自有仓库',
    remark: '华南地区配送中心，24小时运营',
    createTime: '2024-01-17 09:15:00'
  },
  {
    id: 4,
    warehouseCode: 'WH004',
    warehouseName: '成都备件库',
    warehouseType: 'spare_parts',
    warehouseStatus: 'maintenance',
    manager: '赵六',
    contactPhone: '13600136004',
    location: '成都市高新区天府大道4号',
    province: 'sichuan',
    city: '成都市',
    postalCode: '610000',
    longitude: 104.065735,
    latitude: 30.659462,
    capacity: 5000,
    usedCapacity: 3000,
    utilizationRate: 60,
    shelfCount: 100,
    locationCount: 500,
    maxWeight: 200,
    temperatureRange: '0℃ ~ 40℃',
    equipmentList: '叉车×5、货架×100、监控设备×25、消防设备×10',
    safetyFacilities: ['fire_alarm', 'security_camera'],
    specialFeatures: ['dust_proof', 'anti_static'],
    constructionDate: '2018-09-15',
    leaseInfo: '租赁期限：2018-2028年',
    remark: '设备维护中，预计下周恢复正常',
    createTime: '2024-01-18 16:45:00'
  },
  {
    id: 5,
    warehouseCode: 'WH005',
    warehouseName: '杭州退货仓',
    warehouseType: 'return_goods',
    warehouseStatus: 'active',
    manager: '孙七',
    contactPhone: '13500135005',
    location: '杭州市西湖区文三路200号',
    province: 'zhejiang',
    city: '杭州市',
    postalCode: '310000',
    longitude: 120.153576,
    latitude: 30.287459,
    capacity: 3000,
    usedCapacity: 900,
    utilizationRate: 30,
    shelfCount: 60,
    locationCount: 300,
    maxWeight: 150,
    temperatureRange: '5℃ ~ 30℃',
    equipmentList: '叉车×3、货架×60、监控设备×15、消防设备×8',
    safetyFacilities: ['fire_alarm', 'security_camera'],
    specialFeatures: ['dust_proof'],
    constructionDate: '2022-05-20',
    leaseInfo: '租赁期限：2022-2027年',
    remark: '专门处理退货商品，分拣检验',
    createTime: '2024-01-19 11:30:00'
  }
]

// 计算利用率
const computedTableData = computed(() => {
  return tableData.value.map(item => ({
    ...item,
    utilizationRate: item.capacity > 0 ? Math.round((item.usedCapacity / item.capacity) * 100) : 0
  }))
})

// 方法
const getWarehouseTypeColor = (type) => {
  const colors = {
    raw_material: 'primary',
    finished_goods: 'success',
    semi_finished: 'warning',
    spare_parts: 'info',
    return_goods: 'danger'
  }
  return colors[type] || 'info'
}

const getWarehouseTypeLabel = (type) => {
  const labels = {
    raw_material: '原料仓库',
    finished_goods: '成品仓库',
    semi_finished: '半成品仓库',
    spare_parts: '备件仓库',
    return_goods: '退货仓库'
  }
  return labels[type] || type
}

const getWarehouseStatusColor = (status) => {
  const colors = {
    active: 'success',
    maintenance: 'warning',
    inactive: 'danger'
  }
  return colors[status] || 'info'
}

const getWarehouseStatusLabel = (status) => {
  const labels = {
    active: '正常',
    maintenance: '维护中',
    inactive: '停用'
  }
  return labels[status] || status
}

const getUtilizationColor = (rate) => {
  if (rate >= 90) return '#f56c6c'
  if (rate >= 70) return '#e6a23c'
  if (rate >= 50) return '#409eff'
  return '#67c23a'
}

const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    let filteredData = [...mockData]
    
    if (searchForm.warehouseCode) {
      filteredData = filteredData.filter(item => 
        item.warehouseCode.toLowerCase().includes(searchForm.warehouseCode.toLowerCase())
      )
    }
    
    if (searchForm.warehouseName) {
      filteredData = filteredData.filter(item => 
        item.warehouseName.toLowerCase().includes(searchForm.warehouseName.toLowerCase())
      )
    }
    
    if (searchForm.warehouseType) {
      filteredData = filteredData.filter(item => item.warehouseType === searchForm.warehouseType)
    }
    
    if (searchForm.warehouseStatus) {
      filteredData = filteredData.filter(item => item.warehouseStatus === searchForm.warehouseStatus)
    }
    
    tableData.value = filteredData
    pagination.total = filteredData.length
    loading.value = false
    
    ElMessage.success('搜索完成')
  }, 500)
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  loadData()
}

const handleAdd = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新增仓库'
  activeTab.value = 'basic'
  resetFormData()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑仓库'
  activeTab.value = 'basic'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  dialogMode.value = 'view'
  dialogTitle.value = '查看仓库详情'
  activeTab.value = 'basic'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除仓库 "${row.warehouseName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的仓库')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个仓库吗？`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟批量删除
    const selectedIds = selectedRows.value.map(row => row.id)
    tableData.value = tableData.value.filter(item => !selectedIds.includes(item.id))
    pagination.total -= selectedRows.value.length
    selectedRows.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

const handleBatchExport = () => {
  ElMessage.info('批量导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (dialogMode.value === 'add') {
        // 模拟新增
        const newWarehouse = {
          ...formData,
          id: Date.now(),
          createTime: new Date().toLocaleString()
        }
        tableData.value.unshift(newWarehouse)
        pagination.total++
        ElMessage.success('新增成功')
      } else if (dialogMode.value === 'edit') {
        // 模拟编辑
        const index = tableData.value.findIndex(item => item.id === formData.id)
        if (index > -1) {
          Object.assign(tableData.value[index], formData)
          ElMessage.success('编辑成功')
        }
      }
      dialogVisible.value = false
    }
  })
}

const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    warehouseCode: '',
    warehouseName: '',
    warehouseType: '',
    warehouseStatus: 'active',
    manager: '',
    contactPhone: '',
    location: '',
    province: '',
    city: '',
    postalCode: '',
    longitude: null,
    latitude: null,
    capacity: 0,
    usedCapacity: 0,
    shelfCount: 0,
    locationCount: 0,
    maxWeight: 0,
    temperatureRange: '',
    equipmentList: '',
    safetyFacilities: [],
    specialFeatures: [],
    constructionDate: null,
    leaseInfo: '',
    remark: ''
  })
}

const loadData = () => {
  loading.value = true
  // 模拟加载数据
  setTimeout(() => {
    tableData.value = [...mockData]
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.warehouse-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
}

.warehouse-form {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .warehouse-management {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .action-section .el-button {
    width: 100%;
  }
}
</style>